package com.clp.protocol.core.common.frame.time2a;

import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.Date;
import java.util.Objects;

@Getter
@NoArgsConstructor
@AllArgsConstructor
public class CP32Time2a extends Time2a {
    public static int bytesLen = 4;
    /**
     * 时
     */
    private int hour;

    /**
     * 分
     */
    private int minute;

    /**
     * 秒
     */
    private int second;

    /**
     * 毫秒
     */
    private int millisecond;

    @Override
    public CP32Time2a initBy(ByteBuf buf) {
        byte[] bytes = new byte[4];
        buf.readBytes(bytes);
        this.hour = bytes[3] & 0x1F;
        this.minute = bytes[2] & 0x3F;
        int allMs = ((bytes[1] & 0xFF) << 8) + (bytes[0] & 0xFF);
        this.second = allMs / 1000;
        this.millisecond = allMs % 1000;
        return this;
    }

    @Override
    public boolean isValid() {
        if (hour < 0 || hour >= 24) return false;
        if (minute < 0 || minute >= 60) return false;
        if (second < 0 || second >= 60) return false;
        return millisecond >= 0 && millisecond < 1000;
    }

    @Override
    public void writeTo(ByteBuf buf) {
        // 计算总毫秒数
        int allMs = second * 1000 + millisecond;
        // 写入
        buf.writeShortLE(allMs);
        buf.writeByte(minute & 0x3F);
        buf.writeByte(hour & 0x1F);
    }

    @Override
    public Date toDate() {
        throw new UnsupportedOperationException();
    }

    @Override
    public String toString() {
        return "CP32Time2a<" + hour + ":" + minute + ":" + second + ":" + millisecond + ">";
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CP32Time2a that = (CP32Time2a) o;
        return hour == that.hour && minute == that.minute && second == that.second && millisecond == that.millisecond;
    }

    @Override
    public int hashCode() {
        return Objects.hash(hour, minute, second, millisecond);
    }
}
